﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YYNY.Tools;
using YYNY.Tools.Dao;
using System.IO;
using Newtonsoft.Json.Linq;

namespace YYNY.Controllers
{
    public class PurchaseController : Controller
    {
        BaseDao dao = new BaseDao();
        // GET: purchase
        public ActionResult Index()
        {
            return View();
        }


        public ActionResult PurChaseView()
        {
            //获取项目列表
            string sql = "select ProjectId,Name,ProjectCode,Type from t_d_ProjectInfo where IsDelete<>1";
            var ProjectList = dao.GetList(sql, new string[] { "ProjectId", "Name", "ProjectCode", "Type" });
            ViewBag.ProjectList = ProjectList;

            return View();
        }


        public ActionResult MaterialAdd()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            string ProjectId = obj["ProjectId"] == null ? null : obj["ProjectId"].ToString().Replace(" ", "");
            string ProductName = obj["ProductName"] == null ? null : obj["ProductName"].ToString().Replace(" ", "");
            string Specification = obj["Specification"] == null ? null : obj["Specification"].ToString().Replace(" ", "");
            string Unit = obj["Unit"] == null ? null : obj["Unit"].ToString().Replace(" ", "");
            string amount = obj["amount"] == null ? null : obj["amount"].ToString().Replace(" ", "");
            string UnitPrice = obj["UnitPrice"] == null ? null : obj["UnitPrice"].ToString().Replace(" ", "");
            string TotalPrice = obj["TotalPrice"] == null ? null : obj["TotalPrice"].ToString().Replace(" ", "");
            string Memo = obj["Memo"] == null ? null : obj["Memo"].ToString().Replace(" ", "");


            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>()
                {
                    ["ProjectId"] = ProjectId,
                    ["ProductName"] = ProductName,
                    ["Specification"] = Specification,
                    ["Unit"] = Unit,
                    ["amount"] = amount,
                    ["UnitPrice"] = UnitPrice,
                    ["TotalPrice"] = TotalPrice,
                    ["Memo"] = Memo,
                    ["IsDelete"] = 0,
                };
                dao.save("t_d_PurchaseMateriel", map);
                result.Add("result", "OK");

                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        public ActionResult MaterialTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();


            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,PurchaseId,ProductName,Specification,Unit,amount,UnitPrice,TotalPrice,Memo" +
                        "" +
                        " FROM t_d_PurchaseMateriel" +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "PurchaseId", "ProductName", "Specification", "Unit", "amount", "UnitPrice", "TotalPrice", "Memo" });
                SqlNum = "select count(PurchaseId) as TotalNum  FROM t_d_PurchaseMateriel  where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /PurchaseController/MaterialTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }

        }


        public ActionResult MeterialDel()
        {
            string PurchaseId = Request.Form["PurchaseId"] == null ? null : Request.Form["PurchaseId"].ToString().Replace(" ", "");
            string sql = "update t_d_PurchaseMateriel set IsDelete=1 where PurchaseId=" + PurchaseId;

            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                BaseDao.execute(sql);

                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult Upload()
        {


            string tpye = Request.Files[0].ContentType;
            string UpName = Request.Files[0].FileName;
            //获取后缀名
            string exName = UpName.Substring(UpName.LastIndexOf(".") + 1, (UpName.Length - UpName.LastIndexOf(".") - 1));
            string fileName = "Purchase" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + exName;
            if (Directory.Exists(Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMdd"))) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMdd")));
            }
            string filePhysicalPath = Server.MapPath("~/upload/"+ DateTime.Now.ToString("yyyyMMdd")+"/" + fileName);

            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                if (Request.Form["ProjectId"] == "")
                {
                    result.Add("result", "没有选择主项目");
                    return Json(result);
                }

                Request.Files[0].SaveAs(filePhysicalPath);

                Dictionary<string, object> map = new Dictionary<string, object>()
                {
                    ["ProjectId"] = Request.Form["ProjectId"],
                    ["Name"] = UpName,
                    ["Path"] = "/upload/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName,
                    ["TypeName"] = "Purchase",
                    ["IsDelete"]=0
                };
                dao.save("t_d_File", map);

                result.Add("result", "OK");
                return Json(result);
                //upImg.SaveAs(filePhysicalPath);
                //pic = "/upload/" + fileName;
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }

        }

        public ActionResult FileTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();


            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,FileId,ProjectId,Name,Path" +
                        "" +
                        " FROM t_d_File" +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "FileId", "ProjectId", "Name", "Path" });
                SqlNum = "select count(FileId) as TotalNum  FROM t_d_File  where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /PurchaseController/FileTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }

        }

        public ActionResult Download()
        {
            string Path = Request.Form["Path"].ToString();
            string Name = Request.Form["Name"].ToString();
            string filePath = Server.MapPath("~"+Path);//路径
            return File(filePath, "application/unknow", Name); //welcome.txt是客户端保存的名字
        }

        public ActionResult FilelDel()
        {
            string FileId = Request.Form["FileId"] == null ? null : Request.Form["FileId"].ToString().Replace(" ", "");
            string sql = "update t_d_File set IsDelete=1 where FileId=" + FileId;

            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

    }
}